
<template>
  <div class="detail">
    <div class="wrap">
      <div style="margin-top: 60px" class="Breadcrumb">
        <el-breadcrumb separator="/">
          <el-breadcrumb-item :to="{ path: '/' }">全部课程</el-breadcrumb-item>
          <el-breadcrumb-item>课程详情</el-breadcrumb-item>
        </el-breadcrumb>
      </div>

      <div class="courseheader">
        <div class="course-left">
          <img :src="courseDetailList.cover" class="course-cover" />
        </div>
        <div class="course-right">
          <div class="title">课程标题：{{ courseDetailList.title }}</div>
          <div class="lessonNum">
            {{ courseDetailList.viewCount }}人学习
            <el-icon style="color: #ffd700; margin-left: 5px"><Star /></el-icon>
            <el-icon style="color: #ffd700"><Star /></el-icon>
            <el-icon style="color: #ffd700"><Star /></el-icon>
            <el-icon style="color: #ffd700"><Star /></el-icon>
            <el-icon style="color: #ffd700"><Star /></el-icon>
          </div>
          <div class="teacher">讲师名称：{{ teacherInfo.name }}</div>
          <div class="price">
            <div v-if="courseDetailList.price === 0">免费</div>
            <div v-else>￥{{ courseDetailList.price }}</div>
          </div>
          <div class="item">
            <div>
              <el-button
      v-if="courseDetailList.price === 0 || (tableData && tableData[0] && tableData[0].status === 1)"
      type="warning"
      class="participate-btn"
    >
      马上学习
    </el-button>

    <el-button
      v-else
      type="danger"
      @click="dialogTableVisible = true"
      class="participate-btn"
    >
      不可学习
    </el-button>
            </div>
          </div>
        </div>
      </div>

      <div class="center">
        <div class="tabs-container">
          <el-tabs v-model="activeName" class="demo-tabs">
            <el-tab-pane
              label="简介"
              name="first"
              v-html="formattedDescription"
            ></el-tab-pane>
            <el-tab-pane label="课程" name="second">
              <h3>目录</h3>
              <el-divider />
              <div class="courseChapter">
                <ul class="course-list">
                  <li
                    v-for="chapter in chapterList"
                    :key="chapter.id"
                    class="course-item"
                  >
                    <div>
                      <span class="lesson-tag">{{ chapter.title }}</span>
                    </div>
                    <ul>
                      <li v-for="child in chapter.children" :key="child.id">
                        <div class="course-item-wrapper">
                          <span
                            class="video-tag"
                            @click="
                              toVideo(
                                child.videoInfo.id,
                                child.videoInfo.videoSourceId,
                                courseId
                              )
                            "
                            >视频</span
                          >
                          <span class="course-title">{{ child.title }}</span>
                          <span class="course-time">
                            <el-icon><VideoPlay /></el-icon>
                            {{
                              child.videoInfo
                                ? child.videoInfo.duration
                                : "加载中..."
                            }}
                          </span>
                        </div>
                      </li>
                    </ul>
                  </li>
                </ul>
              </div>
            </el-tab-pane>
            <el-tab-pane label="评论" name="third">
              <div class="comments-section">
                <h2>评论区</h2>
                <div
                  v-for="comment in comments"
                  :key="comment.id"
                  class="comment"
                >
                  <img
                    :src="comment.avatar || '../../assets/img/2.jpg'"
                    alt="用户头像"
                    class="avatar"
                  />
                  <div class="comment-content">
                    <span class="nickname">{{ comment.nickname }}</span>
                    <p>{{ comment.content }}</p>
                    <p>{{ comment.gmtCreate }}</p>
                  </div>
                </div>
                <el-input
                  v-model="newComment"
                  style="width: 100%"
                  :rows="4"
                  type="textarea"
                  placeholder="发表评论..."
                />
                <div class="button-Comment">
                  <el-button type="primary" @click="addComment">发布</el-button>
                </div>
              </div>
            </el-tab-pane>
          </el-tabs>
        </div>

        <div class="centerRight">
          <div class="teacher" @click="toTeacher(teacherInfo.id)">
            <div class="img">
              <img :src="teacherInfo.avatar" class="teacher-avatar" />
            </div>
            <div class="name">讲师名称：{{ teacherInfo.name }}</div>
            <div class="intro">简介：{{ teacherInfo.intro }}</div>
          </div>
        </div>

        <el-dialog v-model="dialogTableVisible" title="课程订单" width="80%">
          <div style="margin-bottom: 20px; text-align: right">
            <el-button type="primary" @click="addOrder">添加订单</el-button>
          </div>
          <el-table :data="tableData">
            <el-table-column type="selection" width="55" />
            <el-table-column prop="id" label="序号" width="80" />
            <el-table-column prop="orderNo" label="订单号" width="170" />
            <el-table-column prop="courseTitle" label="课程名称" width="150" />
            <el-table-column label="课程封面" width="150">
              <template #default="scope">
                <div class="courseCover">
                  <img
                    :src="scope.row.courseCover"
                    alt=""
                    style="width: 130px; height: 100px"
                  />
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="teacherName" label="讲师名称" width="180" />
            <el-table-column prop="nickname" label="用户名称" width="100" />
            <el-table-column prop="phone" label="手机号" width="160" />
            <el-table-column prop="totalFee" label="金额" width="160" />
            <el-table-column prop="status" label="订单状态" width="160">
              <template #default="scope">
                <el-tag v-if="scope.row.status === 0" type="success"
                  >未支付</el-tag
                >
                <el-tag v-if="scope.row.status === 1">已支付</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="payType" label="订单支付" width="160">
              <template #default="scope">
                <el-button v-if="scope.row.payType === 1" type="success"
                  >微信支付</el-button
                >
                <el-button
                  v-if="scope.row.payType === 2"
                  @click="toPay(scope.row.id)"
                  >支付宝支付</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-dialog>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, reactive, ref } from "vue";
import { useRouter, useRoute } from "vue-router";
import axios from "../../assets/js/axios";
import { Phone, Star, VideoPlay } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import { jwtDecode } from "jwt-decode";
import { useLoginStore } from "@/stores/login";
import { isGeneratorFunction } from "util/types";

const loginStore = useLoginStore();
const activeName = ref("first");
const courseDetailList = ref<any>({});
const teacherInfo = ref<any>({});
const formattedDescription = ref<string>("");
const chapterList = ref<any>([]);
const newComment = ref("");
const comments = ref<any[]>([]);
const dialogTableVisible = ref(false);
const router = useRouter();
const route = useRoute();
const courseId = route.query.id;
const tableData = ref<any[]>([]);
// 根据课程id查询
if (courseId) {
  axios
    .get(`/serviceedu/edu-course/getCourseId/${courseId}`, {})
    .then((res: any) => {
      if (res.code === 200) {
        courseDetailList.value = res.data.data;
      }
    });

  // 获取课程大纲
  axios
    .get(`/serviceedu/edu-course/getCourseInfo/${courseId}`, {})
    .then((res: any) => {
      if (res.code === 200) {
        const courseDetailInfoList = res.data.data;
        formattedDescription.value = courseDetailInfoList.description.replace(
          /\n/g,
          "<br>"
        );
      }
    });
  //获取课程订单

  // 在获取订单数据后获取 orderId
  if (courseDetailList.value.price !== 0) {
    console.log(courseDetailList.value.price);

    axios
      .get(`/serviceedu/edu-order/getCourseOrder/${courseId}`, {})
      .then((res: any) => {
        console.log("Order Response:", res); // 打印响应以调试
        if (res.code === 200) {
          tableData.value = Array.isArray(res.data.data)
            ? res.data.data
            : [res.data.data];
          console.log("Order", tableData.value);

          // 在这里获取 orderId
          const orderNo = tableData.value[0].orderNo;
          console.log("Order ID:", orderNo);
          console.log("orderId" + orderNo);

          // 继续处理 orderId，例如调用支付方法
        }
      })
      .catch((error) => {
        console.error("获取订单失败", error);
      });
  }

  // 获取讲师
  axios
    .get(`/serviceedu/edu-teacher/getById/${route.query.teacherId}`, {})
    .then((res: any) => {
      if (res.code === 200) {
        teacherInfo.value = res.data.data;
      }
    });

  // 根据章节id查询
  const getChapterList = () => {
    axios
      .get(`/serviceedu/edu-chapter/getChapterList/${courseId}`, {})
      .then((res: any) => {
        if (res.code === 200) {
          chapterList.value = res.data.list;
          chapterList.value.forEach((chapter: any) => {
            if (chapter.children && chapter.children.length > 0) {
              chapter.children.forEach((child: any) => {
                getVideoList(child.id).then((videoData) => {
                  child.videoInfo = videoData;
                });
              });
            }
          });
        }
      });
  };
  getChapterList();
  //课程支付

  // 查询视频
  const getVideoList = (childrenId: number) => {
    return axios
      .get(`/serviceedu/edu-video/getVideo/${childrenId}`, {})
      .then((res: any) => {
        if (res.code === 200) {
          return res.data.data;
        }
      });
  };
}

// 评论区功能
const getComment = () => {
  axios.get("/serviceedu/edu-comment/CommentList", {}).then((res: any) => {
    if (res.code === 200) {
      comments.value = res.data.list;
    }
  });
};
getComment();

const toTeacher = (id: number) => {
  router.push({ path: "/teacherTodetail", query: { id } });
};
const currentVid = ref<number | null>(null);
const toVideo = (vid: number, videoId: number, courseId: any) => {
  console.log("Video Info:", vid, videoId); // 打印以确认
  currentVid.value = vid; // 确保这里传递的是 ID
  router.push({ path: "/video", query: { vid, videoId, courseId } });
};

const token = localStorage.getItem("userToken");
let userInfo = null;
if (token) {
  const decoded: any = jwtDecode(token);
  userInfo = {
    id: decoded.id,
    nickname: decoded.nickname,
    avatar: decoded.avatar || "默认头像路径",
    phone: decoded.phone,
  };
}

const addComment = () => {
  if (!newComment.value.trim()) {
    ElMessage.error("评论内容不能为空");
    return;
  }
  console.log("Current Video ID:", currentVid.value); // 确认当前视频ID

  axios
    .post("/serviceedu/edu-comment/addComment", {
      courseId,
      teacherId: route.query.teacherId,
      videoId: currentVid.value, // 确保这是一个简单的 ID
      userId: loginStore.userInfo.id,
      nickname: loginStore.userInfo.nickname,
      avatar: loginStore.userInfo.avatar,
      content: newComment.value,
    })
    .then((res: any) => {
      if (res.code === 200) {
        ElMessage.success("评论发布成功");
        newComment.value = ""; // 清空评论输入框
        getComment(); // 重新获取评论
      }
    });
};

const addOrder = () => {
  const orderData = {
    courseId,
    courseTitle: courseDetailList.value.title,
    courseCover: courseDetailList.value.cover,
    teacherName: teacherInfo.value.name,
    userId: userInfo?.id,
    nickname: userInfo?.nickname,
    phone: userInfo?.phone,
    totalFee: courseDetailList.value.price,
    payType: 2,
    status: 0,
  };
  axios.post("/serviceedu/edu-order/addOrder", orderData).then((res: any) => {
    if (res.code === 200) {
      ElMessage.success("订单添加成功");
      dialogTableVisible.value = false;
      tableData.value.push(res.data.data); // 更新 tableData
      toPay(); // 直接传递新订单ID到支付函数
    } else {
      ElMessage.error("添加订单失败");
    }
  });
};
const toPay = async () => {
  const courseTitleEncoded = encodeURIComponent(courseDetailList.value.title);
  const orderNoEncoded = encodeURIComponent(tableData.value[0].orderNo);
  const totalFeeEncoded = encodeURIComponent(courseDetailList.value.price);

  const url = `http://y9tdvt.natappfree.cc/alipay/pay?courseTitle=${courseTitleEncoded}&orderNo=${orderNoEncoded}&totalFee=${totalFeeEncoded}`;
  console.log(url);

  window.open(url);

  const checkPaymentStatus = async () => {
    try {
      const response = await axios.post("/serviceedu/edu-course/updateBuyCount/" + courseId, {});
      if (response.status === 200) {
        courseDetailList.value.buyCount += 1; 
        console.log("销售数更新成功");
      } else {
        console.error("销售数更新失败");
      }
    } catch (error) {
      console.error("检查支付状态失败", error);
    }
  };

  // 设置轮询检查支付状态
 checkPaymentStatus() // 每5秒检查一次
};

</script>

<style lang="less" scoped>
.detail {
  background-color: #f7f7f7;
  padding: 20px;

  .courseheader {
    display: flex;
    margin-top: 20px;
    max-width: 1200px;
    height: 290px;
    background-color: #ffffff;
    border-radius: 12px;
    box-shadow: 0 8px 16px rgba(0, 0, 0, 0.1);
    transition: box-shadow 0.3s ease;

    &:hover {
      box-shadow: 0 12px 24px rgba(0, 0, 0, 0.2);
    }

    .course-left {
      margin: 20px;

      .course-cover {
        width: 500px;
        height: 250px;
        border-radius: 10px;
        object-fit: cover;
        transition: transform 0.3s;

        &:hover {
          transform: scale(1.05);
        }
      }
    }

    .course-right {
      margin: 20px;

      .title {
        font-size: 28px;
        color: #333;
        font-weight: bold;
        margin-bottom: 10px;
      }

      .lessonNum {
        font-size: 16px;
        color: #666;
        margin-top: 12px;
        display: flex;
        align-items: center;

        .el-icon {
          transition: transform 0.3s ease;
        }

        &:hover .el-icon {
          transform: scale(1.1);
        }
      }

      .teacher {
        font-size: 20px;
        color: #444;
        margin-top: 15px;
      }

      .price {
        font-size: 30px;
        color: #e74c3c;
        margin-top: 10px;
      }

      .participate-btn {
        margin-top: 30px;
        width: 160px;
        height: 45px;
        background-color: #ff5722;
        color: #fff;
        font-size: 18px;
        border-radius: 6px;
        box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
        transition: background-color 0.3s, box-shadow 0.3s;

        &:hover {
          background-color: #e64a19;
          box-shadow: 0 6px 12px rgba(0, 0, 0, 0.2);
        }
      }
    }
  }

  .center {
    display: flex;
    justify-content: space-between;
    margin-top: 20px;

    .tabs-container {
      width: 900px;
      margin-bottom: 50px;

      .el-tabs__content {
        background-color: #fff;
        border-radius: 10px;
        box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
        padding: 25px;
        font-size: 18px;

        h3 {
          margin-top: 0;
          font-size: 24px;
          font-weight: bold;
          color: #333;
          margin-bottom: 15px;
        }

        .courseChapter {
          margin-top: 20px;
          background-color: #ffffff;
          border-radius: 10px;
          box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
          padding: 20px;
          transition: transform 0.2s; /* 变换过渡效果 */

          &:hover {
            transform: translateY(-5px); /* 悬停时上浮效果 */
          }

          .course-list {
            list-style-type: none; /* 无列表样式 */
            padding-left: 0;

            .course-item {
              height: 50px;
              display: flex;
              justify-content: space-between;
              align-items: center;
              padding: 15px 20px;
              border-bottom: 1px solid #e0e0e0;
              transition: background-color 0.3s, transform 0.2s; /* 背景颜色和变换过渡 */
              cursor: pointer; /* 鼠标悬停时改变为手型光标 */

              &:hover {
                background-color: #f9f9f9; /* 悬停时背景色 */
                transform: scale(1.02); /* 悬停时放大 */
              }
              ul {
                list-style-type: none;
                padding: 0;
                margin: 0;
              }
              .lesson-tag {
                flex-basis: 30%;
                font-weight: bold;
                font-size: 16px;
                color: #2c3e50;
                padding: 5px;
                border-radius: 4px;
                background-color: #e9f7ef;
                text-align: center;
              }

              .course-item-wrapper {
                display: flex;
                align-items: center;
              }

              .course-title {
                flex: 1;
                margin-left: 10px;
                font-size: 18px;
                font-weight: 500;
                white-space: nowrap;
                overflow: hidden;
                text-overflow: ellipsis;
                color: #333;
              }

              .course-time {
                display: flex;
                align-items: center;
                margin-right: 20px;
                font-size: 16px;
                color: #888;
              }
              .video-tag {
                margin-left: -700px;
                width: 40px;
                font-size: 12px;
                border: 1px solid #ff3f29;
                color: #ff3f29;
                height: 20px;
                line-height: 18px;
                text-align: center;
                border-radius: 4px;
                background-color: #ffe8e0;
                transition: background-color 0.3s, transform 0.3s;

                &:hover {
                  background-color: #ff3f29;
                  color: white;
                  transform: scale(1.1);
                }
              }
            }
          }
        }
      }
    }

    .centerRight {
      margin-left: 30px;
      width: 300px;

      .teacher-avatar {
        width: 100%;
        height: 150px;
        border-radius: 12px;
        object-fit: cover;
        box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
        transition: transform 0.3s ease;

        &:hover {
          transform: scale(1.05);
        }
      }

      .name {
        font-size: 20px;
        font-weight: bold;
        color: #333;
        margin-top: 15px;
      }

      .intro {
        font-size: 16px;
        color: #666;
        margin-top: 10px;
      }
    }
  }
  .comments-section {
    margin: 20px;
  }
  .comment {
    display: flex;
    margin-top: 10px;
    margin-bottom: 20px;
  }
  .avatar {
    width: 60px;
    height: 60px;
    border-radius: 50%;
    margin-right: 10px;
  }
  .comment-content {
    p {
      margin-top: 10px;
    }
    .nickname {
      font-weight: bold;
    }
  }
  .button-Comment {
    display: flex;
    justify-content: flex-end; /* 右对齐 */
    margin-top: 10px;
  }
}
</style>
